#!/bin/bash

#    mmbtools-get - Build, install, uninstall, remove the software stack
#    Copyright (C) 2022..2024 Robin ALEXANDER
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

print_info () {
	cut -d= -f 1 -s $mmbconf | while read var; do
		printf "%10s %s\n" "$var" "${!var}";
	done
}

print_usage () {
	cat <<- EOF
		Usage:
			$(basename ${0}) [option] action

			Option:
				-h, --help           Print this help
				-b, --branch <name>  Specify the odr-mmbTools branch to use
				--odr-user <user>    Opendigitalradio user

			Action:
				info                 Print install path info
				install              Install the programs and the configuration sample
				config               Install the configuration sample
				remove               Remove the programs and the configuration sample

	EOF
}

install_base () {
	# Create odr-user if necessary
	if ! test $(id --user "${odr_user}"); then
		useradd --create-home "${odr_user}"
	fi

	## Add the odr user to the dialout and audio groups
	usermod --append --groups audio,dialout "${odr_user}"

	# Install the essential tools and create the tools root directory
	apt-get update
	apt-get install --yes \
		automake \
		build-essential \
		libtool \
		pkg-config \
		supervisor

	if [ ! -d "${DIR_MMB}" ]; then
		mkdir "${DIR_MMB}"
	fi

	if [ ! $(grep inet_http_server /etc/supervisor/supervisord.conf) ]; then
		cat << EOF | tee -a /etc/supervisor/supervisord.conf > /dev/null

[inet_http_server]
port = 8001
username = odr ; Auth username
password = odr ; Auth password
EOF
	fi
}

install_audioenc () {
	# Install mmb-tools: audio encoder
	apt-get install --yes \
		libasound2-dev \
		libcurl4-openssl-dev \
		libjack-jackd2-dev \
		libgstreamer-plugins-base1.0-dev \
		libvlc-dev \
		libzmq3-dev \
		vlc-plugin-base

	if [ ! -d "${DIR_AUDIO}" ]; then
		pushd "${DIR_MMB}" || return
		git clone https://gitee.com/talent518/ODR-AudioEnc.git --branch "${1}"
		popd || return
	fi

	pushd "${DIR_AUDIO}" || return
	./bootstrap
	./configure --enable-alsa --enable-jack --enable-vlc --enable-gst
	make -j$(nproc)
	make install
	make clean
	popd || return
}

install_padenc () {
	# Install mmb-tools: PAD encoder
	apt-get install --yes libmagickwand-dev

	if [ ! -d "${DIR_PAD}" ]; then
		pushd "${DIR_MMB}" || return
		git clone https://gitee.com/talent518/ODR-PadEnc.git --branch "${1}"
		popd || return
	fi

	pushd "${DIR_PAD}" || return
	./bootstrap
	./configure
	make -j$(nproc)
	make install
	make clean
	popd || return
}

install_dabmux () {
	# Install mmb-tools: dab multiplexer
	apt-get install --yes \
		libboost-system-dev \
		libcurl4-openssl-dev \
		libzmq3-dev \
		python3-zmq

	if [ ! -d "${DIR_MUX}" ]; then
		pushd "${DIR_MMB}" || return
		git clone https://gitee.com/talent518/ODR-DabMux.git --branch "${1}"
		popd || return
	fi

	pushd "${DIR_MUX}" || return
	./bootstrap.sh
	./configure
	make -j$(nproc)
	make install
	make clean
	popd || return
}

install_dabmod () {
	# Install mmb-tools: modulator
	apt-get install --yes \
		libbladerf-dev \
		libboost-thread-dev \
		libcurl4-openssl-dev \
		libfftw3-dev \
		liblimesuite-dev \
		libsoapysdr-dev \
		libuhd-dev \
		libzmq3-dev \
		soapysdr-module-all

	if [ ! -d "${DIR_MOD}" ]; then
		pushd "${DIR_MMB}" || return
		git clone https://gitee.com/talent518/ODR-DabMod.git --branch "${1}"
		popd || return
	fi

	pushd "${DIR_MOD}" || return
	./bootstrap.sh
	./configure CFLAGS="-O3 -DNDEBUG" CXXFLAGS="-O3 -DNDEBUG" --enable-fast-math --enable-limesdr --enable-bladerf
	make -j$(nproc)
	make install
	make clean
	popd || return
}

install_encmgr () {
	# Install mmb-tools: encoder manager
	apt-get install --yes \
		python3-cherrypy3 \
		python3-jinja2 \
		python3-pysnmp4 \
		python3-serial \
		python3-yaml \
		$(python3 -c 'import platform;from packaging import version;print("" if version.parse(platform.python_version()) < version.parse("3.12.0") else "python3-pyasyncore")')

	if [ ! -d "${DIR_ENCMGR}" ]; then
		pushd "${DIR_MMB}" || return
		git clone https://gitee.com/talent518/ODR-EncoderManager.git --branch "${1}"
		popd || return
	fi
}

install_config () {
	# Copy the configuration files
	if [ -d "${DIR_CONFIG}" ]; then
		rm -r "${DIR_CONFIG}"
	fi
	cp -rv $(realpath $(dirname $0))/../config "${DIR_CONFIG}"
	ln -sf "${DIR_CONFIG}"/supervisor/*.conf /etc/supervisor/conf.d/

	## Adapt the supervisor configuration files
	for file in ${DIR_CONFIG}/supervisor/*.conf; do
		[[ -e ${file} ]] || break
		sed \
			-e "s;user=pi;user=$(id --user --name ${odr_user});g" \
			-e "s;group=pi;group=$(id --group --name ${odr_user});g" \
			-e "s;@@DIR_CONFIG@@;${DIR_CONFIG};g" \
			-e "s;@@DIR_MUX@@;${DIR_MUX};g" \
			-e "s;@@DIR_ENCMGR@@;${DIR_ENCMGR};g" \
			-i "${file}"
	done

	## Adapt the ODR-EncoderManager configuration file
	sed \
		-e "s;@@DIR_CONFIG@@;${DIR_CONFIG};g" \
		-e "s;@@DIR_ENCMGR@@;${DIR_ENCMGR};g" \
		-e "s;\"user\": \"pi\";\"user\": \"$(id --user --name ${odr_user})\";g" \
		-e "s;\"group\": \"pi\";\"group\": \"$(id --group --name ${odr_user})\";g" \
		-i "${DIR_CONFIG}/encodermanager.json"

	chown --recursive ${odr_user}:${odr_user} ${DIR_MMB}

	## Restart supervisor
	service supervisor restart
	sleep 3
	supervisorctl restart all

	echo "Sample configuration files installed"
}

install () {
	# Clone the sources, build and install programs, clean-up
	install_base "${1}"
	install_audioenc "${1}"
	install_padenc "${1}"
	install_dabmux "${1}"
	install_dabmod "${1}"
	install_encmgr "${1}"
	install_config
	ldconfig

	echo "ODR-mmbTools suite and configuration files installed"
}

remove () {

	# Update supervisor
	rm /etc/supervisor/conf.d/ODR-*
	supervisorctl reread
	supervisorctl reload

	# Uninstall programs
	for makefile in $(ls ${DIR_MMB}/**/Makefile); do
		pushd $(dirname ${makefile}) || return
		make uninstall
		popd || return
	done

	# Delete sources
	rm -rf "${DIR_MMB}"

	# Delete configuration files
	rm -rf "${DIR_CONFIG}"

	echo "ODR-mmbTools suite and configuration files removed"
}

# MAIN PROGRAM
if test "$(id --user)" != "0"; then
	echo "You must be root to run $(basename ${0})" >&2
	exit 2
fi

branch="master"
action=""
odr_user="$(logname || echo -n)"

while [ "$#" -gt 0 ] ; do
	case "${1}" in
		(-h|--help) print_usage; exit 0 ;;
		(-b|--branch) branch="${2}" ; shift ;;
		(--odr-user) odr_user="${2}" ; shift ;;
		info) action="info" ;;
		install) action="install" ;;
		config) action="config" ;;
		remove) action="remove" ;;
		*) print_usage; exit 1 ;;
	esac
	shift
done

if test -z "${odr_user}"; then
	echo "You must use the argument --odr-user" >&2
	exit 3
fi

mmbconf=$(realpath $(dirname $0))/mmbtools-get.conf
source $mmbconf

case "${action}" in
	info)  print_info ;;
	install) install "${branch}" ;;
	config) install_config ;;
	remove) remove ;;
	*) print_usage; exit 3 ;;
esac
